<script lang="ts" setup>
	import { ref, inject } from 'vue'
	import { useStore } from 'vuex'
	import { onShow } from '@dcloudio/uni-app'
	import { checkLogin, msg, showModal } from '@/utils/tools'
	import { checkRegistry } from '@/api/training'
	import { checkCertification, getCertificationInfo, getInitInfo, postUserUpdateInfo } from '@/api/user'
	import { useClearUserInfo } from '@/hooks/user'
	import { SET_USER_INFO } from '@/store/types'
	const $Prefix = inject('$Prefix')
	// #ifndef H5
	const { top, bottom, height } = uni.getMenuButtonBoundingClientRect()
	const headerHeight = (top as number) + (bottom as number) + (height as number)
	// #endif
	// #ifdef H5
	const headerHeight = 70
	// #endif
	const menuList = [
		{
			name: '消息通知',
			img: `${$Prefix}/public/images/smallImage/mine-native.png`,
			build: false,
			url: '/pages/notification/notification',
			isLogin: false
		},
		// {
		// 	name: '训练营报名',
		// 	img: `${$Prefix}/public/images/smallImage/mine-train.png`,
		// 	build: false,
		// 	url: '/pageSignUp/orderFormSign/orderFormSign',
		// 	isLogin: false
		// },
		// {
		// 	name: '赛事报名',
		// 	img: `${$Prefix}/public/images/smallImage/mine-match.png`,
		// 	build: false,
		// 	isLogin: false,
		// 	url: '/pages/matchDetails/matchDetails'
		// },
		{
			name: '我的机构',
			img: `${$Prefix}/public/images/smallImage/mine-code.png`,
			build: false,
			isLogin: true,
			type: 'mechanism'
		},
		// {
		// 	name: '退费审核',
		// 	img: `${$Prefix}/public/images/smallImage/mine-pirce.png`,
		// 	build: true,
		// 	isLogin: true,
		// 	isCoach: true
		// },
		{
			name: '赛事订单',
			img: `${$Prefix}/public/images/smallImage/mine-pirce.png`,
			build: false,
			isLogin: false,
			url: '/pageSignUp/orderMatchSign/orderMatchSign'
		},
		{
			name: '实名认证',
			img: `${$Prefix}/public/images/smallImage/mine-setting.png`,
			build: false,
			isLogin: true,
			type: "certificate",
		},
		{
			name: '设置身份',
			img: `${$Prefix}/public/images/smallImage/mine-train.png`,
			build: false,
			url: '/pages/setRole/setRole',
			isLogin: true
		},
		{
			name: '我的球队',
			img: `${$Prefix}/public/images/smallImage/mine-match.png`,
			build: false,
			url: '/pages/teamTable/teamTable',
			isLogin: true
		},
		{
			name: '退出登录',
			img: `${$Prefix}/public/images/smallImage/loginOut.png`,
			build: false,
			isLogin: true,
			type: 'loginOut'
		}
	]
	const store = useStore()
	const trainingCampInfo = {}
	const userInfoData = ref({})
	const isLogin = ref(false)
	const classInfos = ref([])
	onShow(() => {
		checkLogin(true).then(res => {
			isLogin.value = true
			getInitInfo().then(_res => {
				if (_res.code == 200) {
					userInfoData.value = _res.data
					classInfos.value = _res?.data?.classInfos.map((item : any) => {
						item.responsiblePerson = JSON.parse(item.responsiblePerson)
						return item
					})
				}
			})
		}).catch(err => {
			isLogin.value = false
		})
	})
	const navigatorClick = (data : any) => {
		if (data.build) {
			msg('正在建设中，敬请期待...')
			return false
		}
		checkLogin().then(res => {
			if (data.type == 'mechanism') {
				// 检查机构是否注册
				checkRegistry().then(res => {
					if (res.data) { // 注册
						uni.navigateTo({ url: '/pages/mechanismInfo/mechanismInfo' })
					} else { // 未注册
						uni.navigateTo({ url: '/pages/teamSignUp/teamSignUp' })
					}
				})
			} else if (data.type == 'loginOut') {
				showModal({
					content: '您确定要退出登录吗？',
					confirmText: '退出',
					success: (res) => {
						if (res.confirm) {
							useClearUserInfo()
							// #ifndef H5
							msg('退出成功')
							const time = setTimeout(() => {
								uni.switchTab({ url: '/pages/index/index' })
								clearTimeout(time)
							}, 500)
							// #endif
							//#ifdef H5
							window.close()
							// #endif
						}
					}
				})
			} else if (data.type == "certificate") {
				getCertificationInfo({openid: store.state.user.openId}).then(res => {
					if (res.data) {// 已认证
						uni.navigateTo({ url: '/pages/certificationInfo/certificationInfo' })
					} else {
						uni.navigateTo({ url: '/pages/certification/certification' })
					}
				})
			} else {
				uni.navigateTo({ url: data.url })
			}

		})
	}

	const goNavigateToUrl = (url : string) => {
		// #ifndef H5
		uni.navigateTo({ url })
		// #endif
		// #ifdef H5
		window.location.replace('/#/')
		// #endif
	}

	// 头像选择
	const onChooseAvatar = (data : any) => {
		const userInfo = store.state?.user?.userInfo
		uploadFilePromise(data.detail.avatarUrl).then(res => {
			const _res = JSON.parse(res as string)
			if (_res.code == 200) {
				userInfo.avatarUrl = _res.data.fullUrl
				const params = {
					nickName: userInfo.nickName,
					avatarUrl: userInfo.avatarUrl,
					username: userInfo.username,
				}
				postUserUpdateInfo(params).then(res => {
					uni.setStorageSync('userInfo', userInfo)
					store.commit(`user/${SET_USER_INFO}`, userInfo)
				})
			}
		})
	}
	const uploadFilePromise = (url : any) => {
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: $Prefix + '/api/mobile/file/public/upload', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				success: (res : any) => {
					if (res.statusCode == 200) {
						setTimeout(() => {
							resolve(res.data);
						}, 1000);
					} else {
						setTimeout(() => {
							resolve(false);
						}, 1000);
						msg('上传失败,请重新上传')
					}

				},
			});
		});
	}

	const callPhone = (phone : string) => {
		// #ifndef H5
		uni.openCustomerServiceChat({
			extInfo: { url: 'https://work.weixin.qq.com/kfid/kfc0d02ef22ca7ec8d6' },
			corpId: 'ww2166f77b0b2bd5b3'
		})
		// #endif
		// #ifdef H5
		const a = document.createElement('a')
		a.href = 'https://work.weixin.qq.com/kfid/kfc0d02ef22ca7ec8d6'
		a.click()

		// #endif
		// uni.makePhoneCall({
		//   phoneNumber:phone
		// })
	}
</script>
<template>
	<view class="user-info" :style="{backgroundImage:`url('${$Prefix}/public/images/smallImage/user-bg.png')`}">
		<view class="seizeASeat" :style="{height:`${headerHeight}rpx`}"></view>
		<view class="user-header" v-if="isLogin">
			<view class="avatar">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image :src="store.state?.user?.userInfo?.avatarUrl" />
				</button>
			</view>
			<view class="info" @click="goNavigateToUrl('/pages/mineSetting/mineSetting')">
				<view class="name">
					
					<text>{{store.state?.user?.userInfo?.nickName}} </text>
					<image class="edit-icon" src="https://pro.star.ihehang.com/mini/static/icons/bi.png" mode=""></image>
				</view>
				<!-- <view class="tag-list">
					<view class="tag">{{ userInfoData.userTypeEnumDesc }}</view>
				</view> -->
			</view>
		</view>
		<view class="user-header" v-else @click="goNavigateToUrl('/pageAuth/login/login')">
			<view class="avatar"></view>
			<view class="info">
				<view class="name">登录/注册</view>
			</view>
		</view>
		<view class="user-item" v-if="isLogin">
			<view class="user-title">
				<view class="title">我加入的训练营</view>
				<view class="user-right"
					@click='navigatorClick({url:"/pages/participateInHistory/participateInHistory"})'>
					参加历史
					<up-icon name="arrow-right" color="#818496" size="12"></up-icon>
				</view>
			</view>
			<view class='user-box' v-if="classInfos.length > 0">
				<view class='list-box' :class="{mask: item.pubIfValidEnum == 0}" v-for='(item, index) in classInfos'
					:key='index' :style="{width: `${classInfos.length === 1?'100%':'90%'}`}"
					@click='navigatorClick({url:`/pageSignUp/trainOrder/trainOrder?id=${item.regId}`})'>
					<view class='box-top'
						:style="{backgroundImage: `url('${$Prefix}/public/images/smallImage/min-bg-item.png')`}">
						<view class='box-top-title'>
							<view class='label'>营</view>
							{{ item.campName }}
						</view>
						<view class='box-top-body'>
							<view class='box-top-flex'>
								<view class='top-body-item'>学员姓名：{{ item.name }}</view>
								<view class='top-body-item'>所在班级：{{ item.className }}</view>
							</view>
						</view>
						<view class="box-top-user">
							<view class="box-top-user-item" v-for='(items, indx) in item.responsiblePerson' :key='indx'>
								<view class="user-item-left">
									<image :src='items.avatar[0]?.fullUrl'></image>
								</view>
								<view class="user-item-right">
									<view class="name">{{ items.coachName }}</view>
									<view class="title">{{ items.label }}</view>
								</view>
							</view>
						</view>
					</view>
					<view class='box-time'>
						<view>训练时间</view>
						<view>{{ item.plannedStartTime + '~' + item.plannedCompletionTime}}</view>
					</view>
					<view class='retirement'>
						已退营
					</view>
				</view>
			</view>

			<up-empty v-else width="80px" height="80px" text="暂未参加" textColor="#515462"
				:icon="`${$Prefix}/public/images/smallImage/emty.png`" />
		</view>
		<view class="user-item">
			<view class="user-title">
				<view class="title">我的</view>
			</view>
			<view class="menu-item">
				<view class="menu-gap">
					<block v-for="item in menuList" :key="item.name">
						<block v-if="item.isLogin">
							<block v-if="isLogin">

								<view class="menu-gap-item" @click="navigatorClick(item)" v-if="!item.isCoach">
									<view class="menu-image">
										<image :src="item.img" />
									</view>
									<view class="menu-name">{{item.name}}</view>
								</view>
								<block v-else>
									<view class="menu-gap-item" @click="navigatorClick(item)"
										v-if="userInfoData.userTypeEnum == 1">
										<view class="menu-image">
											<image :src="item.img" />
										</view>
										<view class="menu-name">{{item.name}}</view>
									</view>
								</block>

							</block>

						</block>
						<view class="menu-gap-item" @click="navigatorClick(item)" v-else>
							<view class="menu-image">
								<image :src="item.img" />
							</view>
							<view class="menu-name">{{item.name}}</view>
						</view>
					</block>
				</view>
			</view>
		</view>

		<view class="user-item flex-box" @click="callPhone('028 85582760')">
			<view class="user-label">
				<image :src="`${$Prefix}/public/images/smallImage/phone.png`" />
				<text>联系客服</text>
			</view>
			<view class="user-right">
				<!--        <text>(028)85582760</text>-->
				<u-icon name="arrow-right" size="14" color="#575B66" />
			</view>

		</view>
	</view>
</template>
<style lang="scss" scoped>
	.user-info {
		width: 100%;
		min-height: 100vh;
		background-position: center;
		background-size: cover;
		background-repeat: no-repeat;
		padding: 0 40rpx;

		.user-header {
			display: flex;
			align-items: center;

			.avatar {
				width: 120rpx;
				height: 120rpx;
				overflow: hidden;
				margin-right: 20rpx;
				border-radius: 200rpx;
				border: 2px solid rgba(255, 255, 255, 0.6);
				box-shadow: 0 1px 10px 0 rgba(0, 0, 0, 0.05), 0 4px 5px 0 rgba(0, 0, 0, 0.08), 0 2px 4px -1px rgba(0, 0, 0, 0.12);

				.avatar-wrapper {
					width: 100%;
					height: 100%;
				}

				image {
					width: 100%;
					height: 100%;
				}
			}

			.info {
				.name {
					display: flex;
					align-items: center;
					font-size: 36rpx;
					color: #21252E;
					font-weight: 500;
					.edit-icon{
						flex: 0 0 36rpx;
						width: 36rpx;
						height: 36rpx;
						margin-left: 12rpx;
					}
				}

				.tag-list {
					margin-top: 15rpx;
					display: flex;
					align-items: center;

					.tag {
						border-radius: 200rpx;
						padding: 4rpx 16rpx;
						font-size: 24rpx;
						margin-right: 10rpx;
						color: #5BC7C6;
						border: 1rpx solid #5BC7C6;
						background: rgba(255, 255, 255, 0.6);

						&.fill {
							color: #FFFFFF;
							background-color: #5BC7C6;
						}
					}
				}
			}
		}

		.user-item {
			padding: 24rpx 20rpx;
			background: #FFFFFF;
			margin: 24rpx 0;
			border-radius: 16px;

			.user-title {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.title {
					position: relative;
					font-size: 32rpx;
					color: #21252E;
					padding-left: 16rpx;

					&:before {
						content: '';
						display: block;
						position: absolute;
						height: 32rpx;
						top: calc(50% - 16rpx);
						width: 8rpx;
						left: 0;
						border-radius: 8px 2px 8px 8px;
						background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.6) 100%), #92C75B;
					}
				}

				.user-right {
					display: flex;
					justify-content: center;
					align-items: center;
					color: #818496;
					font-size: 24rpx;

					text {
						font-size: 24rpx;
					}
				}
			}

			.user-box {
				margin-top: 20rpx;
				overflow-x: auto;
				white-space: nowrap;

				.list-box {
					border-radius: 8rpx;
					overflow: hidden;
					display: inline-block;
					background-repeat: no-repeat;
					background-position: center;
					background-size: cover;
					margin-right: 20rpx;
					position: relative;

					.retirement {
						display: none;
					}

					&.mask {
						filter: grayscale(60%);

						.retirement {
							position: absolute;
							display: inline-block;
							top: 0;
							right: 0;
							background-color: rgb(253, 226, 226);
							color: rgb(245, 108, 108);
							font-size: 24rpx;
							padding: 6rpx 12rpx;
							border-bottom-left-radius: 8rpx;
						}
					}

					&:last-child {
						margin-right: 0;
					}

					.box-top {
						width: 100%;
						padding: 24rpx;
						background-repeat: no-repeat;
						background-position: bottom;
						background-size: cover;

						.box-top-title {
							color: #21252E;
							font-size: 28rpx;
							font-weight: 500;
							margin-bottom: 4rpx;
							text-overflow: ellipsis;
							overflow: hidden;
							white-space: nowrap;

							.label {
								display: inline-block;
								border-radius: 8rpx 8rpx 2rpx 8rpx;
								background: #65C071;
								color: #FFFFFF;
								font-size: 20rpx;
								padding: 4rpx 8rpx;
								vertical-align: top;
								font-weight: normal;
							}
						}

						.box-top-body {
							.top-body-item {
								color: #505363;
								font-size: 24rpx;
								font-weight: normal;
							}

							.box-top-flex {
								display: flex;

								.top-body-item {
									margin-right: 40rpx;

									&:last-child {
										margin-right: 0;
									}
								}
							}
						}

						.box-top-user {
							margin-top: 12rpx;
							overflow-x: auto;
							white-space: nowrap;

							.box-top-user-item {
								display: inline-block;
								margin-right: 48rpx;

								&:last-child {
									margin-right: 0;
								}

								.user-item-left {
									display: inline-block;
									width: 72rpx;
									height: 72rpx;
									border-radius: 50%;
									margin-right: 12rpx;
									box-sizing: border-box;
									border: 1px solid #ECEEF1;
									vertical-align: middle;
									overflow: hidden;

									image {
										width: 100%;
										height: 100%;
									}
								}

								.user-item-right {
									display: inline-block;
									vertical-align: middle;

									.name {
										font-size: 28rpx;
										font-weight: normal;
										color: #505363;
									}

									.title {
										font-size: 24rpx;
										font-weight: 350;
										color: #818496;
									}
								}
							}
						}
					}

					.box-time {
						background: rgba(29, 140, 170, 0.08);
						padding: 12rpx 20rpx;
						display: flex;
						justify-content: space-between;
						font-size: 24rpx;
						color: #505363;
					}
				}
			}

			&.flex-box {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.user-label {
				display: flex;
				align-items: center;

				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 20rpx;
				}

				text {
					font-weight: 500;
					font-size: 28rpx;
				}
			}

			.user-right {
				display: flex;
				align-items: center;

				text {
					margin-right: 10rpx;
					color: #8E90A1;
				}
			}
		}

		.menu-gap-item {
			display: inline-block;
			width: calc(100% / 4 - 10rpx);
			margin: 30rpx 5rpx 0 5rpx;
			text-align: center;

			.menu-image {
				width: 50rpx;
				height: 50rpx;
				margin: 0 auto;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.menu-name {
				margin-top: 10rpx;
				font-size: 24rpx;
				color: #505363;
			}
		}
	}
</style>